#include <assert.h>
#include <ctype.h>
#include <locale.h>
#include <errno.h>
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define FILENAME "not_test.txt"

int error_strerror(void)
{
    printf("***** error_strerror *****\n");
    FILE *fout;
    int last_error = 0;

    /*
    There are many reasons fopen can return NULL including (but certainly not limited to):
        The file doesn't exist
        The file is opened in a mode that doesn't allow other accesses
        The network is down
        The file exists, but you don't have permissions
        A file exists with the name you gave, but the current directory of the process is not what you expected so the relative pathname fails to find and open the file.
    The way to find out which is responsible is to dig into the errno code.
    */
    if ( (fout = fopen(FILENAME, "r")) == NULL)
    {
        last_error = errno;
        /* reset errno and continue */
        errno = 0;
    }
    /* do some processing and try opening the file differently, then */

    if (last_error)
    {
        /*
        If perror is not flexible enough, 
        you may obtain 
        a user-readable error description by calling strerror from<string.h>.
        */
        fprintf(stderr, "fopen: Could not open %s for writting: %s\n", FILENAME, strerror(last_error));
        fputs("Cross fingers and continue\n", stderr);
    }
    /* do some other processing */
    return EXIT_SUCCESS;
}


int error_perror(void)
{
    printf("***** error_perror *****\n");
    FILE *fout;

    if ( (fout = fopen(FILENAME, "r")) == NULL )
    {
        /*
        To print a user-readable error message to stderr, 
        call perror from <stdio.h>.

        This will print an error message concerning the current value of errno.
        */
        perror("fopen: Could not open file for writing");
        return EXIT_SUCCESS;
    }
}

void main(void)
{
    error_strerror();
    error_perror();
    system("pause");
}